<?


function cleanURL($str, $replace=array(), $delimiter='-') {
	if( !empty($replace) ) {
		$str = str_replace((array)$replace, ' ', $str);
	}

	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

	return $clean;
}


function getTypeName($type)
	{
		switch($type)
		{
			case "aboutus":
				$title="About Us";
				break;
			case "dealers":
				$title="Dealers &amp; Techies";
				break;	
			case "info":
				$title="Info";
				break;		
			case "faq";	
				$title="FAQ";
				break;
			case "tnc";	
				$title="Terms and Conditions";
				break;
			case "privacy_policy";	
				$title="Privacy Policy";
				break;		
										
			default:
				$title="Invalid! Unknown content type";
				break;
		}
	
		return $title;
	}

function getPageLocation($main,$title,$url)
{
	
	$return = "<a href='index.php'>Main page</a> :: ";
	
	if($main!="")
	{
		$return.=" $main ::";
	}
	
	if($url!="")
	{
		$return.="";
	}
	
	return $return;
}


function productAvatarAdmin($get_product){

		$no=0;
		while($a=mysql_fetch_array($get_product))
		{
			if($no%3==0)
			{
				$tr1="<tr>";
				$tr2="</tr>";
			}
			else
			{
				$tr1="";
				$tr2="";
			}
			
			$get_pic=mysql_query("select * from os_productpic where product_id=".$a['id']." order by order_id asc limit 1");
					
			if(mysql_num_rows($get_pic)==0)
			{
				$pic="empty";
				$piclink="noimage.jpg";
				$fix="";
			}
			else
			{
				$pic=mysql_fetch_array($get_pic,MYSQL_ASSOC);
				
				$piclink=$pic['name'];
				
				if($pic["width"]-$pic["height"]>0)
				{
					$fix="width=155";
				}
				else
				{
					$fix="height=130";
				}
			}	
			
			$get_cat=mysql_query("select * from os_category where id=".$a['cat_id']);
			$get_sub_cat=mysql_query("select * from os_sub_category where id=".$a['sub_cat_id']);
			

	echo $tr1;
	echo "
		<td width='300' height='100%'  valign='top'>
			<table width='100%' height='100%' cellpadding='5' class='solidborder'>
				<td align='center' height='45' valign='top'><strong>".$a['product_name_eng']."</strong></td>
				<tr>
					<td width='100%' align='center' valign='top' height='150'>
					
					<a href='product_viewfull.php?id=".$a['id']."'><img  border=0 src='../productpic/thumbnails/".$piclink."'></a>
					</td>
				</tr>
				<tr>
				<td align='center' valign='bottom'>";
				
				
						
						
				echo "</td></tr>			
				<tr><td align='center' valign='bottom'>";
				$get_price=mysql_query('select unit_price,promotion_price from os_product_inventory where pid='.$a['id'].' order by id asc limit 1');
				
				if(mysql_num_rows($get_price)>0)
				{
					if($a['promotion']==1)
					{
						if($a['promotion_target']=="V")
						{
							$promotion_target="VIP";
							echo "$promotion_target Price : <font class='pricetag_s'>".$_SESSION['currency_code']." ".number_format($_SESSION['currency_rate']*mysql_result($get_price,0,'promotion_price'),2)."</font><br>
							  Normal Price : <font class='pricetag_s'>".$_SESSION['currency_code']." ".number_format($_SESSION['currency_rate']*mysql_result($get_price,0,'unit_price'),2)."</font><br>";
						}else{
							$promotion_target="Promotion";
							echo "$promotion_target Price : <font class='pricetag_s'>".$_SESSION['currency_code']." ".number_format($_SESSION['currency_rate']*mysql_result($get_price,0,'promotion_price'),2)."</font><br>
							  Normal Price : <font class='pricetag_s'><strike>".$_SESSION['currency_code']." ".number_format($_SESSION['currency_rate']*mysql_result($get_price,0,'unit_price'),2)."</strike></font><br>";
						}
						
					}else{
						echo "<font class='pricetag_s'>".$_SESSION['currency_code']." ".number_format($_SESSION['currency_rate']*mysql_result($get_price,0,'unit_price'),2)."</font><br>";
					}
				}else{
					echo "<br>";
				}
						 
				echo "<input type='image' src='../images/button_details.png' onClick='window.open(\"product_viewfull.php?id=".$a['id']."\",\"_self\")'>
					</td>
				</tr>
			</table>
			
		</td>";
	

	$no++;	
		} 

	echo $tr2;

}
function generateMenu()
{
	if(empty($_SESSION['user_role']))
	{
		header("Location:login.php");
		die();
	}
			
	$check=mysql_query("select * from os_user_role where id=".$_SESSION['user_role'])or die(mysql_error());
	
	
	if(checkAccess('allow_content_management',0))
	{
		$_SESSION['allow_content_management']=1;
	}
	
	if(checkAccess('allow_product_management',0))
	{
		$_SESSION['allow_product_management']=1;
				
		if(checkAccess('allow_product_category',0))
		{
			$_SESSION['allow_product_category']=1;
		}
		
		if(checkAccess('allow_product_add',0))
		{
			$_SESSION['allow_product_add']=1;
		}	
				
	}
	
	if(checkAccess('allow_gift_management',0))
	{
		$_SESSION['allow_gift_management']=1;
	}
	
	if(checkAccess('allow_branch_management',0))
	{
		$_SESSION['allow_branch_management']=1;
	}
	
	if(checkAccess('allow_shopping_management',0))
	{
		$_SESSION['allow_shopping_management']=1;
	}
	 
	if(checkAccess('allow_user_management',0))
	{
		$_SESSION['allow_user_management']=1;
		
	}
	 
	 
	if(checkAccess('allow_system_management',0))
	{
		$_SESSION['allow_system_management']=1;
	}
	
	if(checkAccess('allow_shipping_management',0))
	{
		$_SESSION['allow_shipping_management']=1;
	}
}

function checkAccess($access_type,$redirect)
{
	
				
	
	$check=mysql_query("select $access_type from os_user_role where id=".$_SESSION['user_role'])or die(mysql_error());
	if(mysql_num_rows($check)==0)
	{
		
		$return=0;
		if($redirect==1)
		{
			errRedirect("3","Access Denied",$_SERVER['PHP_SELF'],"0");
		}
	}else{
		
		$return=mysql_result($check,0,$access_type);
		if($redirect==1)
		{
			if($return==0)
			{
				errRedirect("3","Access Denied",$_SERVER['PHP_SELF'],"0");
			}
		}
	}
	
	return $return;
	
}
	

	


	
function convertYesNo($value){
		if($value==1)
		{
			$return="Yes";
		}
		else
		{
			$return="No";
		}
		
		return $return;
	
}
		

function convertChecked($value)
{
		if($value==1)
		{
			$return="checked";
		}
		else
		{
			$return="";
		}
		
		return $return;
	
}

function convertStatus($value){
		if($value==1)
		{
			$return="Active";
		}
		else
		{
			$return="Inactive";
		}
		
		return $return;
	
	}
	
function servicepreferred($type)
{
	if($type==1)
	{
		return "C.O.D";
	}
	elseif($type==2)
	{
		return "Pos Express";
	}
	else
	{
		return "Pos Laju";
	}
	
}

function updateInvoice($bid)
{
	$getItem=mysql_query("select * from os_bill_items where bid=$bid");	
	
	if(mysql_num_rows($getItem)>0)
	{
		$grandTotal=0;
		
		while($i=mysql_fetch_array($getItem,MYSQL_ASSOC))
		{
			$totalPrice=$i['quantity']*$i['price'];
			$grandTotal+=$totalPrice;
		}
		
		$update=mysql_query("update os_bill_details set total_amount='$grandTotal' where id=$bid");
	}

}
	
	function verificationCode() 
	{    
		$chars = "abcdefghijkmnopqrstuvwxyz023456789";    
		srand((double)microtime()*1000000);    
		$i = 0;    
		$pass = '' ; 
		   while ($i <= 7) 
		   {   
		        $num = rand() % 33;   
				$tmp = substr($chars, $num, 1);    
				$pass = $pass . $tmp;        
				$i++;    
			}    
		return $pass;
	}
	
function generatePassword() {

    $salt = "1234567890"; 

    srand((double)microtime()*1000000);  

    $i = 0; 
	$pass="";
    while ($i < 10) {  // change for other length

        $num = rand() % 33; 

        $tmp = substr($salt, $num, 1); 

        $pass = $pass . $tmp; 

        $i++; 

    } 

    return $pass;

}

function birthday ($birthday)
  {
    list($year,$month,$day) = explode("-",$birthday);
    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;
    if ($month_diff < 0) $year_diff--;
    elseif (($month_diff==0) && ($day_diff < 0)) $year_diff--;
    return $year_diff;
  }


function dayDiff($time)
{	
	$split_str=explode(" ",$time);
	$date=explode("-",$split_str[0]);
	$time=explode(":",$split_str[1]);
	
	$hour=$time[0];
	$min=$time[1];
	$sec=$time[2];
	
	$year=$date[0];
	$month=$date[1];
	$day=$date[2];
	
	$seconds_dif = mktime(date("H")+8,date("i"),date("s"),date("m"),date("d"),date("Y")) - mktime($hour,$min,$sec,$month,$day,$year); 
	$day=24*60*60;
	
	$day_diff = floor($seconds_dif/$day);
	return $day_diff;
}
function en_id($id)
{
	$enid=($id+99999)*13;
	return $enid;
}

function de_id($id)
{
	$deid=($id/13)-99999;
	return $deid;
}

function timeDiff($time, $opt = array())
{
	// The default values
	$defOptions = array(
		'to' => 0,
		'parts' => 1,
		'precision' => 'second',
		'distance' => TRUE,
		'separator' => ', '
	);
	$opt = array_merge($defOptions, $opt);
	// Default to current time if no to point is given
	(!$opt['to']) && ($opt['to'] = time());
	// Init an empty string
	$str = '';
	// To or From computation
	$diff = ($opt['to'] > $time) ? $opt['to']-$time : $time-$opt['to'];
	// An array of label => periods of seconds;
	$periods = array(
		'decade' => 315569260,
		'year' => 31556926,
		'month' => 2629744,
		'week' => 604800,
		'day' => 86400,
		'hour' => 3600,
		'minute' => 60,
		'second' => 1
	);
	// Round to precision
	if ($opt['precision'] != 'second')
		$diff = round(($diff/$periods[$opt['precision']])) * $periods[$opt['precision']];
	// Report the value is 'less than 1 ' precision period away
	(0 == $diff) && ($str = 'less than 1 '.$opt['precision']);
	// Loop over each period
	foreach ($periods as $label => $value) {
		// Stitch together the time difference string
		(($x=floor($diff/$value))&&$opt['parts']--) && $str.=($str?$opt['separator']:'').($x.' '.$label.($x>1?'s':''));
		// Stop processing if no more parts are going to be reported.
		if ($opt['parts'] == 0 || $label == $opt['precision']) break;
		// Get ready for the next pass
		$diff -= $x*$value;
	}
	$opt['distance'] && $str.=($str&&$opt['to']>$time)?' ago':' away';
	return $str;
}

function unibin2hex($u) {
    $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
    $k1 = bin2hex(substr($k, 0, 1));
    $k2 = bin2hex(substr($k, 1, 1));
    return $k2.$k1;
}

//=============== utf-8 ======================
function hex2str($hex)
{
  $str="";	
  for($i=0;$i<strlen($hex);$i+=2)
  {
    $str.=chr(hexdec(substr($hex,$i,2)));
  }
  $str=$str;
  return $str;
}

function string2hex($str) 
{ 
  if (trim($str)!="") 
  { 
    $hex=""; 
    $str2 = $str;
	$length=strlen($str2); 
    for ($i=0; $i<$length; $i++) 
    { 
       	$bound=""; 
      	$hex.=$bound.str_pad(dechex(ord($str2[$i])), 2, 0, STR_PAD_LEFT); 
      
	} 
    return $hex; 
  } 
}

//============gb2312===============

function hex2str_gb($hex)
{
  $str="";	
  for($i=0;$i<strlen($hex);$i+=2)
  {
    $str.=chr(hexdec(substr($hex,$i,2)));
  }
  return $str;
}

function string2hex_gb($str) 
{ 
  if (trim($str)!="") 
  { 
    $hex=""; 
    $str2 = $str;
	$length=strlen($str2); 
    for ($i=0; $i<$length; $i++) 
    { 
       	$bound=""; 
      	$hex.=$bound.str_pad(dechex(ord($str2[$i])), 2, 0, STR_PAD_LEFT); 
      
	} 
    return $hex; 
  } 
}




?>
